/**
 * 
 */

package controller;

import java.net.URI;
import java.net.URISyntaxException;

import report.DataGatherer;

import jericho_parser_wrapper.PageParser;
import jericho_parser_wrapper.PageRetriever;

/**
 * 
 *
 */
public class SingleThread {
	
	/**
	 * The root seed page url address.
	 */
	private String url;
	
	/**
	 * Instantiates a SingleThread object.
	 * 
	 * @param seed the root URL to start from
	 */
	public SingleThread(final String seed) {
		url = seed;
	}
	
	/**
	 * This method starts the web crawler. It handles
	 * getting new HTML pages, parsers the pages, collects
	 * data, and reports the data.
	 * @throws URISyntaxException if the seed URL is in a invalid format
	 */
	public void execute() throws URISyntaxException {
		final DataGatherer dataGatherer = new DataGatherer();
		
		Spider.urlBuffer.add(new URI(url));
		
		while(Spider.processedPages.get() < Spider.maxPages.get()) {

			if(Spider.urlBuffer.size() > 0) {
				new PageRetriever().run();			
			}
			
			if(Spider.pageBuffer.size() > 0) {
				new PageParser().run();
			}

			if(!dataGatherer.isRunning()) {
				dataGatherer.run();
			}
		}
		System.out.printf("\nURL Size: %-5d Page Buffer Size: %-5d Processed Pages: %d", 
				Spider.urlBuffer.size(), Spider.pageBuffer.size(), Spider.processedPages.get());
	}
}
